<template>
    <div>
        <h1>收到消息：{{ msg }}</h1>
        <!-- 这里可以改成输入框，自定义发送的信息内容 -->
        <button @click="sendMsg">发送测试消息：hello world</button>
    </div>
</template>

<script>

export default {
    name: 'ws-test',
    data() {
        return {
            msg: '',
            ws: null
        }
    },

    created() {
        this.wsinit();
    },

    methods: {
        wsinit() {
            // this.ws = new WebSocket('ws://localhost:9090/websocket');
            this.ws = new WebSocket('ws://localhost:9090/websocket/temp'); // 其中temp为订阅的主题
            this.ws.onopen = (event) => {
              // 一次握手
                console.log('建立连接：' + event);
            }

            this.ws.onclse = (event) => {
                console.log('连接关闭：' + event);
            }

            this.ws.onerror = () => {
                console.log('websocket通信发生错误!');
            }
            // 处理来自服务端发来的数据
            this.ws.onmessage = (event) => {
                console.log('收到消息：' + event.data);
                this.msg = event.data;
            }
            // 设置关闭窗口时断开连接
            window.onbeforeunload = () => {
              this.ws.close();
            }
        },

        // 发送信息给服务端（后端）
        sendMsg(){
            let msg2='hello world';
            this.ws.send(msg2)
        }
    }

}
</script>

<style>

</style>
